import React, { Component } from 'react';
import { View, FlatList, StyleSheet, ActivityIndicator } from 'react-native';
import { List, ListItem } from 'react-native-elements';;
import Loader from './Loader';
import EmptyView from './EmptyView';
import { toast } from '../utils';

const styles = StyleSheet.create({
  spinner: {
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  },
  list: {
    marginTop: 0
  },
  footer: {
    textAlign: 'center',
    color: 'gray'
  }
});

export default class InfinateList extends Component {
  state = {
    refreshing: false,
    loadingMore: false
  }
  renderFooter = () => {
    if (this.state.loadingMore) {
      return (
        <View style={styles.spinner}>
          <ActivityIndicator/>
        </View>
      );
    } else if (!this.props.hideFooter&&this.props.datas&&this.props.datas.length>0) {
      return (
        <ListItem containerStyle={this.props.containerStyle} title={this.props.chinese?'加载更多':'Load More'} titleStyle={styles.footer} hideChevron onPress={this.onLoadMore}/>
      );
    } else {
      return null;
    }
  }
  keyExtractor = (item) => item.id
  onRefresh = () => {
    this.props.refetch()
      .then(() => {
        toast(this.props.chinese?'刷新成功':'Refresh success');
        this.setState({refreshing: false});
      })
    this.setState({refreshing: true});
  }
  onLoadMore = () => {
    this.props.fetchMore()
      .then(() => this.setState({loadingMore: false}));
    this.setState({loadingMore: true});
  }
  render() {
    if (this.props.loading&&!this.props.datas) {
      return <Loader/>;
    } else if (!this.props.hideEmpty&&(!this.props.datas||this.props.datas.length===0)) {
      return <EmptyView/>;
    } else {
      return (
        <List containerStyle={this.props.top?styles.list:null}>
          <FlatList extraData={this.props.extraData?{...this.state, ...this.props.extraData}:this.state}
            data={this.props.datas} keyExtractor={this.keyExtractor}
            renderItem={this.props.renderItem} ListHeaderComponent={this.props.renderHeader}
            ListFooterComponent={this.renderFooter}
            onRefresh={this.onRefresh} refreshing={this.state.refreshing}/>
        </List>
      );
    }
  }
}

